package utils

import (
	"fmt"
	"strings"

	"github.com/pkg/errors"
)

const (
	SystemSettingUrnPrefix    = "settings/"
	UserUrnPrefix             = "users/"
	KnotUrnPrefix             = "knots/"
	ResourceUrnPrefix         = "resources/"
	InboxUrnPrefix            = "inboxes/"
	StorageUrnPrefix          = "storages/"
	IdentityProviderUrnPrefix = "identityProviders/"
	ActivityUrnPrefix         = "activities/"
	SubjectUrnPrefix          = "subjects/"
	TopicUrnPrefix            = "topics/"
	TenantUrnPrefix           = "tenants/"
	ProviderUrnPrefix         = "providers/"
	ModelUrnPrefix            = "models/"
	AssistantUrnPrefix        = "assistants/"
	GranaryUrnPrefix          = "granaries/"
	WorkflowUrnPrefix         = "workflows/"
	ReactionUrnPrefix         = "reactions/"
)

// GetUrnParentTokens returns the tokens from a resource name.
func GetUrnParentTokens(name string, tokenPrefixes ...string) ([]string, error) {
	parts := strings.Split(name, "/")
	if len(parts) != 2*len(tokenPrefixes) {
		return nil, errors.Errorf("invalid request %q", name)
	}

	var tokens []string
	for i, tokenPrefix := range tokenPrefixes {
		if fmt.Sprintf("%s/", parts[2*i]) != tokenPrefix {
			return nil, errors.Errorf("invalid prefix %q in request %q", tokenPrefix, name)
		}
		if parts[2*i+1] == "" {
			return nil, errors.Errorf("invalid request %q with empty prefix %q", name, tokenPrefix)
		}
		tokens = append(tokens, parts[2*i+1])
	}
	return tokens, nil
}

func BuildUrn(prefix string, id int32) string {
	return fmt.Sprintf("%s%d", prefix, id)
}

func BuildSystemKey(prefix string, key string) string {
	return fmt.Sprintf("%s%s", prefix, key)
}

func ExtractIDFromUrn(prefix string, name string) (int32, error) {
	tokens, err := GetUrnParentTokens(name, prefix)
	if err != nil {
		return 0, err
	}
	id, err := ConvertStringToInt32(tokens[0])
	if err != nil {
		return 0, errors.Errorf("invalid user ID %q", tokens[0])
	}
	return id, nil
}
